package com.yc.controller;
import com.mysql.cj.util.StringUtils;
import com.yc.common.utils.AlyExcelUtil;
import com.yc.entity.*;
import com.yc.exception.BizException;
import com.yc.mapper.ClassInfoMapper;
import com.yc.mapper.MajorInfoMapper;
import com.yc.mapper.ScheduleMapper;
import com.yc.mapper.UserMapper;
import com.yc.service.impl.ScheduleServiceImpl;
import com.yc.vo.Course;
import com.yc.vo.Result;
import com.yc.vo.StudentAttendanceRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

@Api(tags = "课程表")
@RestController
@RequestMapping("/schedule")
public class ScheduleController {

    @Resource
    ClassInfoMapper classInfoMapper;

    @Resource
    MajorInfoMapper majorInfoMapper;

    @Resource
    ScheduleMapper scheduleMapper;

    @Resource
    ScheduleServiceImpl scheduleService;

    @Resource
    UserMapper userMapper;


    /**
     * 获取年级和班级
     * @return
     */
    @ApiOperation("获取年级和班级")
    @RequestMapping("getYearAndClass")
    public Result getYear(){
        final List<ClassInfo> classInfos = classInfoMapper.selectList();
        //年级集合
        List<String> yearList = new ArrayList<>();
        //班级集合
        List<String> classList = new ArrayList<>();
        //Map集合，用来存放年级和班级
        Map<String,List<String>> map = new HashMap<>();
        classInfos.forEach(classInfo -> {
            if (StringUtils.isNullOrEmpty(classInfo.getCname())){
                return;
            }
            //班级集合中不包含该班级则存入
            if (!classList.contains(classInfo.getCname())){
                classList.add(classInfo.getCname());
            }
            if (StringUtils.isNullOrEmpty(classInfo.getYearnumber())){
                return;
            }
            //年级集合同上2021
            String str =classInfo.getYearnumber().substring(2,4);
            if (!yearList.contains(str)){
                yearList.add(str);
            }
        });
        //把年级集合和班级集合存入map集合
        yearList.sort((a,b)->{
            return Integer.parseInt(a)-Integer.parseInt(b);
        });
        map.put("yearList",yearList);
        map.put("className",classList);
        //返回数据给前端
        return Result.success(map);
    }


    /**
     * 查询专业
     * @return
     */
    @ApiOperation("查询专业")
    @RequestMapping("queryMajor")
    public Result queryMajor(){
        final List<MajorInfo> majorInfos = majorInfoMapper.selectMajor();
        //存放专业
        List<String> majors = new ArrayList<>();
        majorInfos.forEach(schedule -> {
            if (schedule==null){
                return;
            }
            if (!majors.contains(schedule.getMname())){
                majors.add(schedule.getMname());
            }
        });
        return Result.success(majors);
    }

    /**
     * 查询周次和课程
     * @return
     */
    @ApiOperation("查询课程和教室")
    @RequestMapping("queryCourseNameAndClassroom")
    public Result queryWeeksAndCourseName(){
        final List<Schedule> schedules = scheduleMapper.queryCourseNameAndClassroom();
        //存放课程名称
        List<Map<String,String>> courseName = new ArrayList<>();
        List<String> courseName1 = new ArrayList<>();
        List<Map<String,String>> classroom = new ArrayList<>();
        List<String> classroom1 = new ArrayList<>();
        //存放课程名称和教室
        Map<String,Object> maps = new HashMap<>();
        schedules.forEach(schedule -> {
            if (schedule==null){
                return;
            }
            //前端的el-autocomplete组件需要map值如{value:""}
            if (!courseName1.contains(schedule.getCoursename())){
                //做判断用
                courseName1.add(schedule.getCoursename());
                //保存返回的课程数据
                Map<String,String> map = new HashMap<>();
                map.put("value",schedule.getCoursename());
                courseName.add(map);
            }

            if (!classroom1.contains(schedule.getClassroom())){
                classroom1.add(schedule.getClassroom());
                Map<String,String> map = new HashMap<>();
                map.put("value",schedule.getClassroom());
                classroom.add(map);
            }
        });
        maps.put("courseName",courseName);
        maps.put("classroom",classroom);
        return Result.success(maps);
    }

    /**
     * 分页查询课程信息
     * @param course 课程信息
     * @return
     */
    @ApiOperation("分页查询课程信息")
    @PostMapping("queryCourse")
    public Result queryCourse(@RequestBody Course course){
        String nowYear = (LocalDateTime.now()+"").substring(0,4);
        course.setNowYear(nowYear);
        final String classtime = course.getClasstime();
        //节次格式为1~2
        if (classtime.indexOf("~") != -1){
            final String[] split = classtime.split("~");
            course.setClasstime1(split[0]);
            course.setClasstime2(split[1]);
        }
        Map<Integer, String> weekMap= new HashMap<>();
        weekMap.put(1,"星期天");
        weekMap.put(2,"星期一");
        weekMap.put(3,"星期二");
        weekMap.put(4,"星期三");
        weekMap.put(5,"星期四");
        weekMap.put(6,"星期五");
        weekMap.put(7,"星期六");

        //分页查询,第3个参数设置获取查询的总行数
        List<Course> data = scheduleMapper.selectCoursePage(course);
        if(data!=null && !data.isEmpty()){
            data.stream().forEach(item->{
                item.setWeekStr(weekMap.get(item.getIsweek()));
            });
        }
        int total = scheduleMapper.selectTotal(course) ;
        //存储总行数 与记录数
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("data",data);
        return Result.success(map);
    }

    /**
     * 根据课程id删除课程,并且根据时间判断是否合法
     * @param schedule
     * @return
     */
    @ApiOperation("根据课程id删除课程")
    @RequestMapping("deleteCourse")
    public Result deleteCourse(@RequestBody Schedule schedule) throws BizException {
        scheduleMapper.deleteById(schedule);
        return Result.success("删除成功");
    }

    /**
     * 修改和添加数据
     * @param schedule
     * @return
     * @throws BizException
     */
    @ApiOperation("修改和添加数据")
    @RequestMapping("save")
    public Result save(@RequestBody Schedule schedule) throws BizException {
        scheduleService.insert(schedule);
        return Result.success("数据保存成功");
    }


    @ApiOperation("查询专业和年级")
    @RequestMapping("selectClassByMajorAndYear")
    public List<String> selectClassByMajorAndYear(@RequestParam("mname") String mname,@RequestParam("year")String year){
        final List<String> list = classInfoMapper.selectClassByMajorAndYear(mname,year);
        return list;
    }

    /**
     * 查询上课老师
     * @return
     */
    @ApiOperation("查询上课老师")
    @RequestMapping("queryTeachers")
    public List<String> selectTeachers(){
        final List<User> users = userMapper.selectListUser();
        List<String> data = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getRoles()!=null){
                if (users.get(i).getRoles().contains("3")){
                    if (!data.contains(users.get(i))){
                        String str = users.get(i).getNickname()+" "+users.get(i).getUsername();
                        data.add(str);
                    }
                }
            }
        }
        return data;
    }

    @ApiOperation("根据时间查询上课周次")
    @RequestMapping("selectWeek")
    public Integer selectWeek(String date){
        Integer week= scheduleMapper.selectWeek(date);
        return week;
    }

    @ApiOperation("文件上传,批量添加课程")
    @RequestMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //List<String> teacherList = scheduleService.batchAddScedule(AlyExcelUtil.handleScheduleInfo(inputStream));

        List<String> teacherList = scheduleService.upload(inputStream);
        List<String> newTeacherList = new ArrayList<>();
        //去重teacherList
        teacherList.forEach(list->{
            if (!newTeacherList.contains(list)){
                newTeacherList.add(list);
            }
        });
        return Result.success(newTeacherList);
    }

    /**
     * 异常捕获
     * @param e
     * @return
     */
    @ApiOperation("Biz异常捕获")
    @ExceptionHandler(BizException.class)
    public Result BizExceptionHandler( BizException e){
        return Result.error(e.getMessage());
    }


    @ApiOperation("根据老师Id查询上课信息")
    @GetMapping("/schedule/get/{teacherId}")
    public Result selectScheduleByTeacherId(@ApiParam(name = "teacherId", value = "老师Id", required = true)
                                            @PathVariable("teacherId") String teacherId){
        List<StudentAttendanceRecord> studentAttendanceRecords = scheduleService.selectScheduleByTeacherId(teacherId);
        return Result.success(studentAttendanceRecords);
    }

}
